package org.xurui.sxl.protocol.utils;

import io.netty.buffer.Unpooled;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SxlMessageUtils {
    public static String CMD_PREFIX = "*";
    public static String CMD_SUFFIX = "#";
    public static String CMD_SEPARATION = ",";

    public static void bulidAndSend2DeviceV4Msg(FromDeviceMessageContext context,
                                                String zzs,
                                         String deviceId,
                                         String cmd,
                                         String seq){
        //TODO 暂时关闭V4回复，不然会造成所有下发指令不可用
//        if(1==1) return;
        SimpleDateFormat dateFormat=new SimpleDateFormat("HHmmss");
        String time = dateFormat.format(new Date());
        context.getSession()
            .send(SxlMessageUtils.SxlCmd
                .getInstance()
                .appendAndAddSeparator(zzs)
                .appendAndAddSeparator(deviceId)
                .appendAndAddSeparator("V4")
                .appendAndAddSeparator(cmd)
                .appendAndAddSeparator(seq)
                .append(time)
                .buildEncodeMessage()).subscribe();

    }

    public static String getTimeHHMMSS(){
        SimpleDateFormat dateFormat=new SimpleDateFormat("HHmmss");
        String time = dateFormat.format(new Date());
        return time;
    }

    public static class SxlCmd{
        StringBuffer sb = new StringBuffer();
        public static SxlCmd getInstance(){
            SxlCmd instance = new SxlCmd();
            instance.sb.append(SxlMessageUtils.CMD_PREFIX);
            return instance;
        }

        public SxlCmd appendAndAddSeparator(String item){
            sb.append(item.trim());
            sb.append(SxlMessageUtils.CMD_SEPARATION);
            return this;
        }

        public SxlCmd append(String item){
            sb.append(item.trim());
            return this;
        }

        public String buildCmd(){
            sb.append(SxlMessageUtils.CMD_SUFFIX);
            return sb.toString();
        }

        public EncodedMessage buildEncodeMessage(){
            return EncodedMessage
                .simple(Unpooled.wrappedBuffer(buildCmd().getBytes()));
        }
    }
}
